package com.mall.security;

import com.mall.bean.SysUser;
import com.mall.bean.User;
import com.mall.service.SysUserService;
import com.mall.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by xiaochao on 2017/7/24.
 */
public class SecurityRealm extends AuthorizingRealm {

    private static final Logger LOGGER = LoggerFactory.getLogger(SecurityRealm.class);

    @Autowired
    private SysUserService userService;


    /**认证*/
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token){
        UsernamePasswordToken usertoken = (UsernamePasswordToken) token;
        String username = usertoken.getUsername();
        String password = new String(usertoken.getPassword());
        System.out.println(username);

        SysUser user = userService.selectByUsernamePassword(username,password);
        if (user == null) {//
            throw new AuthenticationException("用户名/密码错误");
        }
        if("1".equals(user.getLocked()) ){
            throw new AuthenticationException("该用户已禁用");
        }
        LOGGER.info("用户:[{}],密码[{}]", username, user.getPassword());

        Subject sub = SecurityUtils.getSubject();
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,password, ByteSource.Util.bytes(username),this.getName());
        sub.getSession().setAttribute("user", user);
        return authenticationInfo;
    }


    /**授权*/
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }



}
